package com.cart.musicdemo.receiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.hardware.usb.UsbManager;
import android.widget.Toast;

public class USBReceiver extends BroadcastReceiver {

    private LoadApp loadApp;

    private StopApp stopApp;

    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();

        // USB插入识别
        if (UsbManager.ACTION_USB_DEVICE_ATTACHED.equals(action)
            || Intent.ACTION_MEDIA_MOUNTED.equals(action)) {
            // 插入检测成功后，就回调LoadApp.init()方法进行app初始化
            Toast.makeText(context, "USB设备已插入", Toast.LENGTH_SHORT).show();
            loadApp.init();
        } else if (UsbManager.ACTION_USB_DEVICE_DETACHED.equals(action)
            || Intent.ACTION_MEDIA_UNMOUNTED.equals(action)) {
            // 拔出
            Toast.makeText(context, "USB设备已拔出", Toast.LENGTH_SHORT).show();
            stopApp.destroy();
        }
    }

    public void setStopApp(StopApp stopApp) {
        this.stopApp = stopApp;
    }

    public void setLoadApp(LoadApp loadApp) {
        this.loadApp = loadApp;
    }

    public interface LoadApp {
        void init();
    }

    public interface StopApp {
        void destroy();
    }
}
